package com.xuanyang.dormrepair.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.xuanyang.dormrepair.config.hook.AppLogin;
import com.xuanyang.dormrepair.config.hook.OnceLogin;
import com.xuanyang.dormrepair.model.entity.Advise;
import com.xuanyang.dormrepair.model.entity.FloorRoom;
import com.xuanyang.dormrepair.service.AdviseService;
import com.xuanyang.dormrepair.utils.Const;
import com.xuanyang.dormrepair.utils.RestResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * @AUTHOR soft
 * @DATE 2019/5/23 18:33
 * @DESCRIBE 建议
 */
@RestController
@RequestMapping("/api/advise")
public class AdviseController {

    @Autowired
    private AdviseService adviseService;

    private FloorRoom room;

    @ModelAttribute
    public void init(@RequestAttribute(value = Const.USER, required = false) FloorRoom rm) {
        this.room = rm;
    }

    @OnceLogin
    @PostMapping("/page")
    public RestResponse page(int page, int limit, Advise query) {
        IPage<Advise> iPage = adviseService.page(page, limit, query);
        if (iPage.getTotal() > 0) {
            iPage.getRecords().forEach(advise -> {
                if (advise.getHideName()) {
                    advise.setRoom(null);
                }
            });
            return RestResponse.ok(iPage);
        }
        return RestResponse.fail();
    }

    @AppLogin
    @PostMapping("/self")
    public RestResponse self(int page, int limit, Advise query) {
        query.setFloorId(room.getId());
        return this.page(page, limit, query);
    }

    @AppLogin
    @PostMapping("/add")
    public RestResponse add(Advise advise) {
        advise.setFloorId(room.getId());

        if (advise.getHideName() == null || !advise.getHideName()) {
            if (StringUtils.isEmpty(advise.getName())) {
                advise.setName(room.getName());
            }
        } else {
            advise.setName("匿名");
        }
        if (adviseService.add(advise)) {
            return RestResponse.ok();
        }
        return RestResponse.fail();
    }

    @OnceLogin
    @PostMapping("/del/{id}")
    public RestResponse del(@PathVariable Integer id) {
        if (adviseService.delete(id)) {
            return RestResponse.ok();
        }
        return RestResponse.fail();
    }

    @AppLogin
    @PostMapping("/change")
    public RestResponse change(Advise advise) {
        if (adviseService.update(advise)) {
            return RestResponse.ok();
        }
        return RestResponse.fail();
    }
}
